<template>
            <section>
              <!--工具条-->
              <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="query">
                  <el-form-item>
                    <el-input v-model="query.keyword" placeholder="角色名称/sn"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" v-on:click="getQueryRoles">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="this.pageInfo.dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="角色名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="sn" width="120" sortable>
			</el-table-column>
			<el-table-column label="操作" width="300">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handleAuth(scope.$index, scope.row)">授权</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="this.query.pageSize" :total="this.pageInfo.total" style="float:right;">-->
<!--			</el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.query.currentPage"
          :page-sizes="[5,10,15,20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.pageInfo.total"
          style="float:right">
      </el-pagination>

		</el-col>

		<!--新增/修改界面-->
		<el-dialog   title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="角色名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="sn" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
<!--权限设置界面-->
              <el-dialog title="设置权限" :visible.sync="setPermissionVisible" :close-on-click-modal="false">
                <el-form :model="rolePermission" label-width="80px" ref="saveForm">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">
                    <template>
                      <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                                   v-model='rolePermission.permissionSns' :label="p.sn"
                                   @change='handleCheck(1,indexkey)'>
                        {{p.name}}
                      </el-checkbox>
                      <div style="margin-bottom: 20px;">
                        <div v-for="c in p.children" class="line-check" :key="c.sn"
                             style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                          <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                                       v-model="rolePermission.permissionSns" :label="c.sn">
                            {{c.name}}
                          </el-checkbox>
                        </div>
                      </div>
                    </template>
                  </div>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click.native="saveFormVisible = false">取消</el-button>
                  <el-button type="primary" @click.native="saveRolePermission" :loading="saveLoading">提交</el-button>
                </div>
              </el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				query: {
					keyword: '',
          currentPage:1,
          pageSize:5
				},
        pageInfo:{
          dataList: [],
          total: 0,
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名字', trigger: 'blur' }
					]
				},
				//编辑界面数据
				// editForm: {
				// 	id: 0,
				// 	name: '',
				// 	sex: -1,
				// 	age: 0,
				// 	birth: '',
				// 	addr: ''
				// },

				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入角色名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入角色sn', trigger: 'blur' }
          ]
				},
				//新增界面数据
				saveForm: {
				  id:null,
          name:"",
          sn:""
				},
        setPermissionVisible:false,//控制授权弹框是否显示
        rolePermission:{
				  id:null,
          permissionSns:[]     //角色的权限集合
        },
        isIndeterminate:false,//控制复选框不确定的状态
         checkAll:false,   //控制表示全选框是否为全选状态
        permissionTree:[],   //表示所有权限数据
        saveLoading:false,
        allPermissionSns:[]

			}
		},
		methods: {
		  //保存权限
      saveRolePermission(){
        this.$http.post("/role/permission/",this.rolePermission)
            .then(result=>{
              console.log(result);
              result=result.data
              if (result.success){
                this.$message({
                  message: '保存成功',
                  type: 'success'
                });
                this.setPermissionVisible=false
              }else{
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              this.$message({
                message: '系统错误',
                type: 'error'
              });
            })
      },
      handleCheckAllChange(val){
        this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheck(type, a = 0) {
        // 多选框
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
        let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
        if (type == 2) { // 二级菜单点击
          let index = 0;  //
          this.permissionTree[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.rolePermission.permissionSns.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
                this.rolePermission.permissionSns.push(item.sn)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
                this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
              }
            })
          }
        }
        // 获取已选中的长度
        let checkedCount = this.rolePermission.permissionSns.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allPermissionSns.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
      },
		  //授权
      handleAuth(index,row){
        this.getPermissionTree()
        this.setPermissionVisible=true
        this.rolePermission.id=row.id
        this.getRolePermissionById(this.rolePermission.id)
      },
      getRolePermissionById(id){
        this.$http.get("/role/permission/"+id)
            .then(result=>{
              console.log(result);
              result=result.data
              if (result.success){
                this.rolePermission.permissionSns=result.resultObj
              }else{
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
            })
            .catch(result=>{
              this.$message({
                message: '系统错误',
                type: 'error'
              });
            })
      },
      //获取权限树的方法
      getPermissionTree(){
        this.$http.get("/permission")
            .then(result=>{
              console.log(result);
              result=result.data
              if (result.success){

                this.permissionTree=result.resultObj
                for(let i=0;i<this.permissionTree.length;i++){
                  let p = this.permissionTree[i];
                  this.allPermissionSns.push(p.sn);
                  let c = p.children;
                  if(c){
                    for(let j=0;j<c.length;j++){
                      this.allPermissionSns.push(c[j].sn);
                    }
                  }
                }
              }else{
              }
            })
            .catch(result=>{

            })
      },
		  handleSizeChange(val){

		    this.query.pageSize=val;
		    this.getRoles()
      },
		  getQueryRoles(){
		    this.query.currentPage=1
        this.getRoles()
      },
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
      //分页显示转换为第1页
			handleCurrentChange(val) {
        console.log(val);
				this.query.currentPage = val;
        this.getRoles()
      },
			getRoles() {
				// let para = {
				// 	page: this.page,
				// 	name: this.filters.name
				// };
				this.listLoading = true;
				//NProgress.start();
        this.$http.put("/role",this.query)
            .then(result=>{
              console.log(result);
              result=result.data
             if (result.success){
               this.$message({
                 message: '查询成功',
                 type: 'success'
               });
               this.listLoading = false;
               console.log(result);
               this.pageInfo=result.resultObj
               console.log(this.pageInfo.dataList)
             }else{
               this.$message({
                 message: '查询失败',
                 type: 'danger'
               });
             }
            })
            .catch(result=>{

            })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/role/"+row.id)
          .then(result=>{
            result=result.data
            if (result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.listLoading = false;
              this.query.currentPage=1
              this.getRoles()
            }else{
              this.$message({
                message: '删除失败',
                type: 'danger'
              });
            }
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
				this.saveForm = Object.assign({}, row)
			},
			//显示新增界面
			handleAdd: function () {
				this.saveFormVisible = true;
				this.saveForm = {
          id:null,
          name:"",
          sn:""
        }
			},
			//新增
			addSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
                .then(() => {
                  this.addLoading = true;
                  //NProgress.start();
                  let para = Object.assign({}, this.saveForm);

                  this.$http.post("/role", para)
                      .then(result => {
                        result = result.data
                        if (result.success) {
                          this.$message({
                            message: '保存成功',
                            type: 'success'
                          });
                          this.addLoading = false;
                          this.saveFormVisible=false;
                          this.getRoles()
                        } else {
                          this.$message({
                            message: '保存失败',
                            type: 'danger'
                          });
                        }
                      })
                      .catch(result => {
                        this.$message({message: "网络异常，请检查网络", type: "danger"})
                      })
                       }).catch({})
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          //NProgress.start();
          this.$http.patch("/role",ids)
              .then(result => {
                result = result.data
                if (result.success) {
                  this.$message({
                    message: '批量删除成功',
                    type: 'success'
                  });
                  this.listLoading = false;
                  this.query.currentPage = 1
                  this.getRoles()
                } else {
                  this.$message({
                    message: '批量删除失败',
                    type: 'danger'
                  });
                }
              })
              .catch(result=>{

                })
              })
              .catch(() => {

              });
        }
		},
		mounted() {
			this.getRoles();
		}
	}

</script>

<style scoped>

</style>